import sys
import re
import os

import pysvn

help_message = """
    Usage: python merge_branch.py BRANCH_NAME
    Merge branch back into trunk.  This script will do everyting except
    the final commit (so you can test that the merge is working properly).
    """

if len(sys.argv) != 2:
    print help_message
else:
    branch_name = sys.argv[1]
    if os.path.exists(branch_name):
        print ">>>Preparing to merge branch named '%s' back into trunk." % branch_name
    else:
        print "    !! Invalid branch name. !!"
        print help_message
        sys.exit()


client = pysvn.Client()

logs = client.log("https://computational-neuroscience.googlecode.com/svn")

# find the last merge of branch
branch_revision = False
for log in logs:
    match = re.search('merg.*%s.*to.*trunk' % branch_name, log.message.lower())
    if match is not None:
        print '---------------Latest "branch merge" log message ---------------------'
        print log.message
        print '---------------          END             -----------------------------\n'
        branch_revision = log.revision
        break

# if we didn't find any merges, find the branch point.
if branch_revision is False:
    for log in logs:
        match = re.search('add.*%s.*branch' % branch_name, log.message.lower())
        if match is not None:
            print '---------------Latest "added branch" log message ---------------------'
            print log.message
            print '---------------          END             -----------------------------\n'
            branch_revision = log.revision
            break

if branch_revision:
    print "Found the revision of branch creation (or last merge) to be: %s" % str(branch_revision)

    current_revision = logs[0].revision
    print '---------------Latest commit log message -----------------------------'
    print logs[0].message
    print '---------------          END             -----------------------------\n'
    print "Found the latest commited revision of branch to be: %s" % str(current_revision)
    print ">>>Updating to the most current version of trunk from repostiory."
    client.update('../trunk')

    print ">>>Merging to trunk..."
    client.merge("./%s" % branch_name, branch_revision, # starting from here
                 './%s' % branch_name,current_revision, # find out how to get here
                 "../trunk") # apply those changes to here
    print "Done."
else:
    print "Branch named '%s' not in repository." % branch_name

